package com.iap.client.mediator
{
	import com.iap.app.AppGlobal;
	import com.iap.client.view.client.ClientEditWindow;
	import com.iap.client.view.client.ClientListWindow;
	import com.iap.common.event.ClientLiteEvent;
	import com.iap.common.mediator.BaseMediator;
	import com.iap.common.model.ClientLite;
	import com.iap.common.signal.ClientLiteRequestSignal;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	import spark.events.GridEvent;

	public class ClientListWindowMediator extends BaseMediator
	{
		[Inject]
		public var view:ClientListWindow;
		[Inject]
		public var clientRequest:ClientLiteRequestSignal;

		private var clientEditWindow:ClientEditWindow;

		override public function onRegister():void
		{
			view.grid.addEventListener(GridEvent.GRID_CLICK, clientGridClickHandler);
			view.addButton.addEventListener(MouseEvent.CLICK, addClickHandler);
			addContextListener(ClientLiteEvent.RESPONSE, clientResponseHandler);
		}
		
		private function clientResponseHandler(evt:ClientLiteEvent):void
		{
			AppGlobal.endWait();
			if(evt.response.task == ClientLiteRequestSignal.GET)
			{
				view.clientData = new ArrayCollection(evt.response.result as Array);
			}
		}

		private function clientGridClickHandler(evt:GridEvent):void
		{
			var item:ClientLite = evt.item as ClientLite;
			if(item == null) return;
			openClientEdit(item);
		}
		
		private function addClickHandler(evt:MouseEvent):void
		{
			openClientEdit(new ClientLite());
		}
		
		private function openClientEdit(client:ClientLite):void
		{
			clientEditWindow = new ClientEditWindow();
			clientEditWindow.model = client;
			PopUpManager.addPopUp(clientEditWindow, view.root, true);
			PopUpManager.centerPopUp(clientEditWindow);
			clientEditWindow.addEventListener(CloseEvent.CLOSE, clientEditCloseHandler);
			view.root.addEventListener(Event.RESIZE, clientEditResizeHandler);
		}

		private function clientEditResizeHandler(evt:Event):void
		{
			PopUpManager.centerPopUp(clientEditWindow);
		}
		
		private function clientEditCloseHandler(evt:Event):void
		{
			view.root.removeEventListener(Event.RESIZE, clientEditResizeHandler);
			clientEditWindow.removeEventListener(CloseEvent.CLOSE, clientEditCloseHandler);
			clientRequest.dispatch(new ClientLite(), ClientLiteRequestSignal.GET);
		}
	}
}